package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import javax.xml.transform.Result;

import static android.os.Environment.getDataDirectory;
import static android.os.Environment.getExternalStorageDirectory;

public class DaliyCountActivity extends AppCompatActivity implements View.OnClickListener {
    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;

    //全局提示;
    Toast curToast;
    private ProgressDialog waitDialog = null;
    //顶部元素
    TextView txt_titleInv;
    Button btn_LoginUser, btn_LoginClose;
    //布局元素;
    ListView empDaliyList;
    EditText edit_ViewDate;
    Button btn_viewRefresh;
    TextView view_orderNoText,view_styleNoText,view_styleSortText;
    TextView view_empNoText,view_empNameText,view_workNameText;
    EditText view_numEdit,edit_debug;
    Button view_oneBtn,view_twoBtn,view_threeBtn,view_fourBtn,view_fiveBtn,
            view_sixBtn,view_sevenBtn,view_eightBtn,view_nineBtn,view_zeroBtn,
            view_okBtn,view_delBtn,view_clrBtn,btn_saveData;

    //全局变量
    String curLoginUserNo,curLoginUser,serviceUrl="",curDepartNo="",curDepart="",curProduceMasterID="",
            curStyleID="",curOrderNo ="", curStyleNo ="",curStyleSort="",curFactory="";//操作员所属部门等信息;
    String CPUID;
    boolean overWriteSign;
    int curPlaceCount,curOperateTime;
    //当前选中的内容;
    private String selEmpID="",selEmpNo="",selEmpName="",selWorkName="",curDate="",language="";
    private int selRowIndex;//当前选中的行;
    private JSONArray daliyCountJSONArray;

    //核心设置的代码
    protected void switchLanguage() {
        //读取配置文件-设置语言
        String STORE_NAME = "Settings";
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        language=settings.getString("language",language);
        //获取资源
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = new Locale("en","");
                resources.updateConfiguration(config, dm);
                break;
            case "km":
                config.locale = new Locale("km","");
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设定语言
        switchLanguage();
        //启动Activity
        setContentView(R.layout.activity_daliycount);
        hideBottomUIMenu();
        //全屏;
        try{
            //取存储路径;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //SD卡准备好的话，优先存储;
                SaveFilePath = getExternalStorageDirectory().toString();
                Log.d("msg","用存储卡:"+SaveFilePath);
            }
            else{
                //系统内部Flash;
                SaveFilePath =this.getFilesDir().toString();
                Log.d("msg","用系统目录:"+SaveFilePath);
            }
            //组织并判断是否需要创建Root目录;
            SaveFilePath = SaveFilePath +"/BDMES";
            Log.d("msg","存储目录为:"+SaveFilePath);
            //判断是否需要创建BDMES根目录;
            if (isExternalStorageWritable()==true) {
                //主目录;
                File file = new File(SaveFilePath);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath );
                //数据库目录
                file = new File(SaveFilePath +SaveDBFolder);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath +SaveDBFolder);
            }
        } catch (Exception e){
            Toast.makeText(this,String.valueOf("出错了，"+e.getMessage()),Toast.LENGTH_LONG).show();
        }
        //创建对话框，
        waitDialog=new ProgressDialog(this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curFactory=paramBundle.getString("curFactory");
        curDepartNo=paramBundle.getString("curDepartNo");
        curDepart=paramBundle.getString("curDepart");
        curProduceMasterID=paramBundle.getString("curProduceMasterID");
        curStyleID=paramBundle.getString("curStyleID");
        curOrderNo=paramBundle.getString("curOrderNo");
        curStyleNo=paramBundle.getString("curStyleNo");
        curStyleSort=paramBundle.getString("curStyleSort");
        curPlaceCount=paramBundle.getInt("PlaceCount");
        curOperateTime=paramBundle.getInt("OperateTime");
        serviceUrl=paramBundle.getString("serviceUrl");
        CPUID=paramBundle.getString("CPUID");
        System.out.println(paramBundle);
        //初始化按键，并将页面加载到fragment列表中;
        InitView();
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        //创建表;
        CreateDBTable();
        btn_LoginUser.setText(curLoginUser);
    }


    //创建数据库表
    private void CreateDBTable(){
        if (mainDB!=null) {
            //建表语句;
            System.out.println("CreateDBTable--------------Start");
            //员工表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS DaliyCount (ID INTEGER PRIMARY KEY AUTOINCREMENT,EmpID VARCHAR,EmpNo VARCHAR,EmpName VARCHAR," +
                    " WorkNo VARCHAR,WorkName VARCHAR,DaySewNum int,DayOverNum int,RemainNum int,RptNum int)");
        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }


    // /判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    private void InitView() {
        //顶部元素
        txt_titleInv=(TextView)findViewById(R.id.txt_titleInv);
        txt_titleInv.setText(getString(R.string.daliyCount));
        btn_LoginUser=(Button)findViewById(R.id.btn_LoginUser);
        btn_LoginUser.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return false;
            }
        });
        btn_LoginClose=(Button)findViewById(R.id.btn_LoginClose);
        btn_LoginClose.setOnClickListener(this);
        //表格
        empDaliyList=(ListView)findViewById(R.id.empDaliyList);
        empDaliyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                //置选择制单信息;
                try {
                    selEmpNo= daliyCountJSONArray.getJSONObject(position).getString("EmpNo");
                    selEmpName= daliyCountJSONArray.getJSONObject(position).getString("EmpName");
                    selWorkName=daliyCountJSONArray.getJSONObject(position).getString("WorkName");
                    selRowIndex=position;
                    view_empNoText.setText(selEmpNo);
                    view_empNameText.setText(selEmpName);
                    view_workNameText.setText(selWorkName);
                    view_numEdit.setText(daliyCountJSONArray.getJSONObject(position).getString("RptNum"));
                    view_numEdit.setSelection(view_numEdit.getText().length());
                    overWriteSign=true;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("ViewFragment..............................2");
        //表头
        edit_ViewDate=(EditText)findViewById(R.id.edit_ViewDate);
        edit_ViewDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(DaliyCountActivity.this, null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,getString(R.string.Finish),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_ViewDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,getString(R.string.Cancel),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.show();

            }
        });
        edit_ViewDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        System.out.println("ViewFragment..............................3");
        btn_viewRefresh=(Button)findViewById(R.id. btn_viewRefresh);
        btn_viewRefresh.setOnClickListener(this);
        btn_saveData=(Button)findViewById(R.id.btn_saveData);
        btn_saveData.setOnClickListener(this);
        //界面显示
        view_orderNoText=(TextView)findViewById(R.id.view_orderNoText);
        view_styleNoText=(TextView)findViewById(R.id.view_styleNoText);
        view_styleSortText=(TextView)findViewById(R.id.view_styleSortText);
        view_empNoText=(TextView)findViewById(R.id.view_empNoText);
        view_empNameText=(TextView)findViewById(R.id.view_empNameText);
        view_workNameText=(TextView)findViewById(R.id.view_workNameText);
        view_numEdit=(EditText)findViewById(R.id.view_numEdit);
        view_numEdit.setInputType(InputType.TYPE_NULL);
        edit_debug=(EditText)findViewById(R.id.edit_debug);
        System.out.println("ViewFragment..............................4");
        //界面按键
        view_oneBtn=(Button)findViewById(R.id.view_oneBtn);
        view_oneBtn.setOnClickListener(this);
        view_twoBtn=(Button)findViewById(R.id.view_twoBtn);
        view_twoBtn.setOnClickListener(this);
        view_threeBtn=(Button)findViewById(R.id.view_threeBtn);
        view_threeBtn.setOnClickListener(this);
        view_fourBtn=(Button)findViewById(R.id.view_fourBtn);
        view_fourBtn.setOnClickListener(this);
        view_fiveBtn=(Button)findViewById(R.id.view_fiveBtn);
        view_fiveBtn.setOnClickListener(this);
        view_sixBtn=(Button)findViewById(R.id.view_sixBtn);
        view_sixBtn.setOnClickListener(this);
        view_sevenBtn=(Button)findViewById(R.id.view_sevenBtn);
        view_sevenBtn.setOnClickListener(this);
        view_eightBtn=(Button)findViewById(R.id.view_eightBtn);
        view_eightBtn.setOnClickListener(this);
        view_nineBtn=(Button)findViewById(R.id.view_nineBtn);
        view_nineBtn.setOnClickListener(this);
        view_zeroBtn=(Button)findViewById(R.id.view_zeroBtn);
        view_zeroBtn.setOnClickListener(this);
        view_okBtn=(Button)findViewById(R.id.view_okBtn);
        view_okBtn.setOnClickListener(this);
        view_delBtn=(Button)findViewById(R.id.view_delBtn);
        view_delBtn.setOnClickListener(this);
        view_clrBtn=(Button)findViewById(R.id.view_clrBtn);
        view_clrBtn.setOnClickListener(this);

        System.out.println("ViewFragment..............................5");
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        edit_ViewDate.setText(DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()-1 * 24 * 60 * 60 * 1000)));
        //初始提醒;
        curToast = Toast.makeText(this, getString(R.string.SystemHint), Toast.LENGTH_LONG);
        view_orderNoText.setText(curOrderNo);
        view_styleNoText.setText(curStyleNo);
        view_styleSortText.setText(curStyleSort);
    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_viewRefresh:
                //调用存储过程刷新数据;
                refreshDaliyCountList(curDepartNo,edit_ViewDate.getText().toString(),curOrderNo,curStyleNo,curStyleSort,curLoginUserNo);
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1=(Button)v.findViewById(v.getId());
                if (overWriteSign==true) {
                    view_numEdit.setText(tmpBtn1.getText());
                    overWriteSign=false;
                } else view_numEdit.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (view_numEdit.getText().length()>0)
                {
                    overWriteSign=false;
                    view_numEdit.setSelection(view_numEdit.getText().length());
                    System.out.println(view_numEdit.getSelectionStart());
                    int start=view_numEdit.getSelectionStart();
                    view_numEdit.getText().delete(start-1,start);
                }
                break;
            case R.id.view_okBtn:
                if (view_numEdit.getText().length()==0)
                {
                    curToast.setText(getString(R.string.PlsInputDataNum));
                    curToast.show();
                    return;
                }
                System.out.println("--------------------A------------------");
                System.out.println(selRowIndex);
                System.out.println("--------------------B------------------");
                if (selRowIndex>=0){
                    if (daliyCountJSONArray!=null)
                    {
                        try {
                            daliyCountJSONArray.getJSONObject(selRowIndex).put("RptNum",view_numEdit.getText());
                            //更新显示;
                            ((BaseAdapter)empDaliyList.getAdapter()).notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case R.id.btn_saveData:
                if (CheckDaliyCount()==true) {
                    SaveDaliyCount(curDepartNo, curOrderNo, curStyleNo, curStyleID, curStyleSort, edit_ViewDate.getText().toString());
                }
                break;
            case R.id.view_clrBtn:
                view_numEdit.setText("");
                break;
            case R.id.btn_LoginClose:
                    this.finish();
                break;
            default:
                break;
        }
    }

    //显示员工状态;
    private void showDaliyCount(){
        Log.d("msg","showDaliyCount----------->刷新数据");
        final DaliyAccountListAdapter daliyAccountListAdapter =new DaliyAccountListAdapter(this);
        empDaliyList.setAdapter(daliyAccountListAdapter);
    }


    //刷新工序列表;
    private void refreshDaliyCountList(String paramDepart,String paramDate,String paramOrderNo,String paramStyleNo,String paramStyleSort,String paramUserNo)
    {
        selRowIndex=-1;
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap.put("SqlComm", "Exec ScenePAD_GetDaliyCount @DepartmentNo='" + paramDepart + "',@CurDate='"+paramDate+ "',@OrderNo='"+paramOrderNo
                + "',@StyleNo='"+paramStyleNo+ "',@StyleSort='"+paramStyleSort+"',@UserNo='"+paramUserNo+"'");
        //调用WebService过程并处理界面更新;
        Log.d("msg","serviceUrl------------------"+serviceUrl);
        ReadSQLData(serviceUrl, methodName, paramMap);
    }


    public void ReadSQLData(String serviceUrl,String methodName,Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                Boolean ErrSign=false;
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                //置参数给对象
                String namespace="http://tempuri.org/";
                SoapObject soapObject=new SoapObject(namespace, methodName);
                SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                //遍列Map数组加参数
                Map<String,Object> paramMap= (Map<String,Object>) params[0].get("paramMap");
                Iterator iterator = paramMap.keySet().iterator();
                while (iterator.hasNext())
                {
                    String paramkey = (String) iterator.next();
                    String paramvalue = (String) paramMap.get(paramkey);
                    soapObject.addProperty(paramkey,paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                }
                //准备执行WebService
                envelope.dotNet=true;
                envelope.setOutputSoapObject(soapObject);
                HttpTransportSE httpTranstation=new HttpTransportSE(serviceUrl,10000);
                try {
                    //执行调用WebService;
                    httpTranstation.call(namespace+methodName, envelope);
                    //获取返回会值;
                    Object result=envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr=(String) result.toString();
                    System.out.println(resultstr);
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign=true;
                    soapFault.printStackTrace();
                } catch (XmlPullParserException e) {
                    ErrSign=true;
                    e.printStackTrace();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign==true)  Log.d("msg","查询数据出错,错误异常抛出！");
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null)
                {
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    return;
                }
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    JSONArray jsonArray = new JSONArray(s);
                    //往界面转数据;
                    if (jsonArray.length()>0)
                    {
                        Log.d("onPostExecute","ReadSQLData--------------------1");
                        //返回的为状态数据;
                        if (jsonArray.optJSONObject(0).has("GetDaliyCount")==true)
                        {
                            //关闭ProgressDialog
                            waitDialog.hide();
                            Log.d("msg","GetDaliyCount--------------------2");
                            daliyCountJSONArray =jsonArray;
                            //刷新员工状态数据;
                            showDaliyCount();
                        }
                    }
                    //关闭ProgressDialog
                    waitDialog.hide();
                } catch (JSONException e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    waitDialog.hide();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        }.execute(params);

    }

    //检查数据,报数不能超过今日检验数
    private boolean CheckDaliyCount() {
        if (daliyCountJSONArray == null) return false;
        System.out.println(daliyCountJSONArray);
        mainDB.execSQL("Delete from DaliyCount");
        if (daliyCountJSONArray.length() > 0) {
            for (int i = 0; i < daliyCountJSONArray.length(); i++) {

                if ((daliyCountJSONArray.optJSONObject(i).has("RemainNum") == true) && (daliyCountJSONArray.optJSONObject(i).has("RptNum") == true)) {
                    try {
                        //保存数据
                        mainDB.execSQL("INSERT INTO DaliyCount(EmpID,EmpNo,EmpName,WorkNo,WorkName,RemainNum,RptNum) VALUES (?,?,?,?,?,?,?)",
                                new Object[]{daliyCountJSONArray.optJSONObject(i).getString("EmpID"), daliyCountJSONArray.optJSONObject(i).getString("EmpNo"),daliyCountJSONArray.optJSONObject(i).getString("EmpName"),
                                        daliyCountJSONArray.optJSONObject(i).getString("WorkNo"),daliyCountJSONArray.optJSONObject(i).getString("WorkName"),daliyCountJSONArray.optJSONObject(i).getString("RemainNum"),
                                        daliyCountJSONArray.optJSONObject(i).getString("RptNum")});

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
            //判断各个工序的总报数
            Cursor curma = mainDB.rawQuery("SELECT WorkNo,WorkName,RemainNum,sum(RptNum) RptNum FROM DaliyCount Group by WorkNo,WorkName,RemainNum",
                    new String[]{});
            System.out.println("Check Proc OutNum------------------b");
            while (curma.moveToNext()){
                int tmpRemainNum=curma.getInt(curma.getColumnIndex("RemainNum"));
                int tmpRptNum=curma.getInt(curma.getColumnIndex("RptNum"));
                String tmpWorkNo=curma.getString(curma.getColumnIndex("WorkNo"));
                String tmpWorkName=curma.getString(curma.getColumnIndex("WorkName"));
                System.out.println(tmpRemainNum+":"+tmpRptNum+":"+tmpWorkNo+":"+tmpWorkName);
                // 创建对话框
                if (tmpRemainNum<tmpRptNum) {
                    String resultText=tmpWorkNo+":"+tmpWorkName+getString(R.string.DaliyRptNumError);
                    AlertDialog alertDialog = new AlertDialog.Builder(DaliyCountActivity.this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(resultText)
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).create();
                    alertDialog.show(); // 显示对话框
                    return false;
                }
            }
            return  true;
        }
        return  false;
    }
    //保存工序安排
    private void SaveDaliyCount(String paramDepartNo, String paramOrderNo, String paramStyleNo,String paramStyleID,String paramStyleSort,String paramWorkDate) {
        if (daliyCountJSONArray==null) return;
        if (daliyCountJSONArray.length()>0)
        {
            JSONArray tmpArrangeList = null;
            try {
                tmpArrangeList=new JSONArray("[]");
                for (int i=0;i<daliyCountJSONArray.length();i++)
                {
                    try {
                        JSONObject empProcJSON = new JSONObject();
                        empProcJSON.put("EmpOperNumID",daliyCountJSONArray.getJSONObject(i).getString("EmpOperNumID"));
                        empProcJSON.put("EmpID",daliyCountJSONArray.getJSONObject(i).getString("EmpID"));
                        empProcJSON.put("CardID",daliyCountJSONArray.getJSONObject(i).getString("CardID"));
                        empProcJSON.put("EmpNo",daliyCountJSONArray.getJSONObject(i).getString("EmpNo"));
                        empProcJSON.put("WorkNo",daliyCountJSONArray.getJSONObject(i).getString("WorkNo"));
                        empProcJSON.put("RptNum",daliyCountJSONArray.getJSONObject(i).getString("RptNum"));
                        tmpArrangeList.put(empProcJSON);
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //调用WebService将数据保存至服务器;
            Log.d("SaveDaliyCount","SaveDaliyCount-----------------------------------------Upload");
            //执行WebService过程
            String methodName="SaveDaliyCount";
            //通过哈希数组来传递参数;
            Map<String,Object> paramMap=new HashMap<String,Object>();
            //可传递多个参数  paramMap.put(paramName, paramValue);
            paramMap.put("paramDepartNo", paramDepartNo);
            paramMap.put("paramOrderNo", paramOrderNo);
            paramMap.put("paramStyleNo", paramStyleNo);
            paramMap.put("paramStyleID",paramStyleID);
            paramMap.put("paramStyleSort",paramStyleSort);
            paramMap.put("paramWorkDate",paramWorkDate);
            paramMap.put("paramDaliyJSON", tmpArrangeList.toString());
            paramMap.put("paramUserNo", curLoginUserNo);
            System.out.println(tmpArrangeList.toString());
            //调用WebService过程并处理界面更新;
            GetWebData(serviceUrl, methodName, paramMap);
        }

        Log.d("SaveDaliyCount","SaveDaliyCount-----------------------------------------Over");
    }


    public void GetWebData(String serviceUrl,String methodName,Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                waitDialog.show();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign=false;
                try {
                    String serviceUrl= (String) params[0].get("serviceUrl");
                    System.out.println(serviceUrl);
                    String methodName= (String) params[0].get("methodName");
                    System.out.println(methodName);
                    //置参数给对象
                    String namespace = "http://tempuri.org/";
                    SoapObject soapObject = new SoapObject(namespace, methodName);
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    //遍列Map数组加参数
                    Map<String, Object> paramMap = (Map<String, Object>) params[0].get("paramMap");
                    Iterator iterator = paramMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String paramkey = (String) iterator.next();
                        String paramvalue = (String) paramMap.get(paramkey);
                        soapObject.addProperty(paramkey, paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                    }
                    //准备执行WebService
                    envelope.dotNet = true;
                    envelope.setOutputSoapObject(soapObject);
                    HttpTransportSE httpTranstation = new HttpTransportSE(serviceUrl, 10000);
                    //执行调用WebService;
                    httpTranstation.call(namespace + methodName, envelope);
                    //获取返回会值;
                    Object result = envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr = (String) result.toString();
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("A.服务异常，请与系统管理员联系!\r\n"+e.getMessage());
                    curToast.show();
                } catch (SoapFault e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("B.服务异常，请与系统管理员联系!\r\n"+e.getMessage());
                    curToast.show();
                } catch (XmlPullParserException e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("C.服务异常，请与系统管理员联系!\r\n"+e.getMessage());
                    curToast.show();
                } catch (SocketTimeoutException e){
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("D.服务异常，请与系统管理员联系!\r\n"+e.getMessage());
                    curToast.show();
                } catch (IOException e) {
                    ErrSign=true;
                    e.printStackTrace();
                    curToast.setText("E.服务异常，请与系统管理员联系!\r\n"+e.getMessage());
                    curToast.show();
                }
                //关闭ProgressDialog
                if (ErrSign==true) {
                    Log.d("msg","查询数据出错,错误异常抛出！");
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                System.out.println("----------------------------onPostExecute----------------------------");
                if (s==null)
                {
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    return;
                }
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    waitDialog.hide();//收到信息后取消提示;
                    //转换数据;
                    JSONArray jsonArray = new JSONArray(s);
                    if (jsonArray.length()>0) {
                        if (jsonArray.getJSONObject(0).has("PROCRESULT")==true) {
                            String resultMsg = jsonArray.optJSONObject(0).getString("PROCRESULT");
                            //提示提交完成，需确认;
                            // 创建对话框
                            AlertDialog alertDialog = new AlertDialog.Builder(DaliyCountActivity.this)
                                    .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                    .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create();
                            alertDialog.show(); // 显示对话框
                        }
                    }
                    Log.d("msg","onPostExecute转换完成，准备显示。。。。。。。。");
                } catch (JSONException e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    if (waitDialog.equals(null)==false) waitDialog.hide();
                    curToast.setText(e.getMessage());
                    curToast.show();
                }
            }
        }.execute(params);

    }



    //员工状态表格适配器;
    public final class DaliyAccountListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DaliyAccountListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return daliyCountJSONArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return daliyCountJSONArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.daliycount_listhead, null, false);
            int listWidth=parent.getWidth();//防止不显示，主要是宽度不对;
            convertView.setBackground(getResources().getDrawable(R.drawable.orderlist_selector));
            convertView.setLayoutParams(new ListView.LayoutParams((int)listWidth,(int)(40)));
            int textColor=0;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                int textBlackColor = getResources().getColor(R.color.text_black);
                int textBlueColor = getResources().getColor(R.color.text_blue);
                int textRedColor = getResources().getColor(R.color.text_red);
                textColor=textBlackColor;
                if (daliyCountJSONArray.optJSONObject(position).has("RowState")==true) {
                    if (daliyCountJSONArray.optJSONObject(position).get("RowState").toString().equals("1") == true)
                        textColor = textBlueColor;
                    if (daliyCountJSONArray.optJSONObject(position).get("RowState").toString().equals("2") == true)
                        textColor = textRedColor;
                }
                TextView tv = (TextView) convertView.findViewById(R.id.text_view_EmpName);// 显示文字
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("EmpNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_WorkNo);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("WorkNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_WorkName);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("WorkName").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_SewNum);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("SewNum").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_OverNum);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("OverNum").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_DaySewNum);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("DaySewNum").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_DayOverNum);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("DayOverNum").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_AccountNum);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("AccountNum").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_RemainNum);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("RemainNum").toString());
                tv = (TextView) convertView.findViewById(R.id.text_view_RptNum);// 显示文字
                tv.setTextColor(textColor);
                tv.setText(daliyCountJSONArray.optJSONObject(position).get("RptNum").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","OrderGridAdapter_position:"+position);
            return convertView;
        }
    }

}
